package com.easyadmin.modules.sys.controller;

import cn.hutool.core.codec.Base64;
import com.easyadmin.common.context.UserContext;
import com.easyadmin.common.web.base.BaseController;
import com.easyadmin.common.web.domain.response.Result;
import com.easyadmin.common.web.domain.response.ResultCode;
import com.easyadmin.modules.sys.domain.SysImageInfo;
import com.easyadmin.modules.sys.service.ISysImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;

/**
 * 图片文件内容Controller
 *
 * @author jmys
 * @date 2025-10-08
 */
@RestController
@RequestMapping("/sys/image")
public class SysImageController extends BaseController {

    private String prefix = "sys/image";

    @Autowired
    private ISysImageService sysFileInfoService;

    @GetMapping("/main")
//    @PreAuthorize("hasPermission('/sys/fileInfo/main','sys:fileInfo:main')")
    public ModelAndView main() {
        return jumpPage(prefix + "/index");
    }

    /**
     * 加载图片
     */
    @GetMapping("/show/{id}")
//    @PreAuthorize("hasPermission('/sys/fileInfo/data','sys:fileInfo:data')")
    public ResponseEntity<InputStreamResource> downloadImage(
            @PathVariable Long id) {
        SysImageInfo sysImageInfo = sysFileInfoService.selectById(id);
        try {
            // 1. 解码Base64字符串为二进制数组
            String base64Data = sysImageInfo.getFileContent();
            // 去除可能的data URL前缀（如：data:image/png;base64,）
            if (base64Data.contains(",")) {
                base64Data = base64Data.split(",")[1];
            }

            byte[] binaryData = Base64.decode(base64Data);

            // 2. 创建输入流
            InputStream inputStream = new ByteArrayInputStream(binaryData);

            // 3. 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition",
                    "attachment; filename=\"" + sysImageInfo.getFileName() + "\"");
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");

            // 4. 根据文件类型设置Content-Type
            String contentType = getContentType(sysImageInfo.getFileType());
            headers.setContentType(MediaType.parseMediaType(contentType));

            // 5. 返回文件流
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(binaryData.length)
                    .body(new InputStreamResource(inputStream));

        } catch (Exception e) {
            throw new RuntimeException("文件下载失败: " + e.getMessage());
        }
    }


    private String getContentType(String fileType) {
        switch (fileType.toLowerCase()) {
            case "pdf":
                return "application/pdf";
            case "png":
                return "image/png";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "txt":
                return "text/plain";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            default:
                return "application/octet-stream";
        }
    }


    /**
     * 新增图片文件内容
     */
    @ResponseBody
    @PostMapping("/save")
    /*@PreAuthorize("hasPermission('/sys/fileInfo/add','sys:fileInfo:add')")*/
    public Result save(@RequestBody SysImageInfo sysImageInfo) {
        sysImageInfo.setCreateBy(UserContext.currentUser().getUsername());
        sysFileInfoService.save(sysImageInfo);
        return success(ResultCode.SUCCESS.getCode(), "上传成功", sysImageInfo.getId());
    }


    /**
     * 删除图片文件内容
     */
    @ResponseBody
    @DeleteMapping("/batchRemove")
//    @PreAuthorize("hasPermission('/sys/fileInfo/remove','sys:fileInfo:remove')")
    public Result batchRemove(String ids) {
        return decide(sysFileInfoService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 删除图片文件内容
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
//    @PreAuthorize("hasPermission('/sys/fileInfo/remove','sys:fileInfo:remove')")
    public Result remove(@PathVariable("id") Long id) {
        return decide(sysFileInfoService.removeById(id));
    }
}
